<template>
  <div class="body3">
    <div id="write">
      <div>
        <a-textarea
          v-model:value="noticeValue"
          placeholder="请输入公告内容"
          allow-clear
          style="width: 400px; height: 300px"
        />
      </div>
      <div style="text-align: center; margin-top: 30px">
        <a-button @click="send()">发送</a-button>
      </div>
    </div>
    <div id="history">
      <a-list size="large" bordered :data-source="data" :pagination="true">
        <template #renderItem="{ item }">
          <a-list-item>
            <div id="list">
              <span>发布时间为 {{ item.time }}</span>
              <span>{{ item.content }}</span>
            </div>
            <a-button
              type="primary"
              ghost
              style="margin-left: 10px"
              @click="deleteNotices(item)"
            >
              删除
            </a-button>
          </a-list-item>
        </template>
        <template #header>
          <div>公告历史</div>
        </template>
      </a-list>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref } from "vue";
import io from "../units/socket.js";
import { doNotice, getNotices, deleteNotice } from "../../api/message.js";
import { formatTime } from "../units/date";
import { message } from "ant-design-vue";

export default defineComponent({
  setup() {
    const noticeValue = ref("");
    const data = ref([]);

    const deleteNotices = (item) => {
      deleteNotice({
        url: "/admin/deleteNotice",
        time: item.time,
        success: (res) => {
          message.info(res.data);
          location.reload();
        },
        err: (err) => {
          console.log(err);
        },
      });
    };

    getNotices({
      url: "/admin/getNotices",
      success: (res) => {
        // console.log(res.data);
        data.value = res.data;
      },
      err: (err) => {
        console.log(err);
      },
    });

    const send = () => {
      let dateNow = formatTime();
      doNotice({
        url: "/admin/doNotice",
        time: dateNow,
        content: noticeValue.value,
        success: (res) => {
          // console.log(res.data);
          io.emit("sendNotice", { data: "您收到了一条系统通知" });
          message.info(res.data);
          data.value.push({ time: dateNow, content: noticeValue.value });
          noticeValue.value = "";
        },
        err: (err) => {
          console.log(err);
        },
      });
    };

    return {
      noticeValue,
      data,
      send,
      deleteNotices,
    };
  },
});
</script>

<style scoped>
.body3 {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
}
#write {
  margin: 0 30px 0 20px;
}
#history {
  min-width: 300px;
  max-width: 500px;
}
#list {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
</style>